package com.yylending.las.authority.rsa;

import android.text.TextUtils;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.network.NetworkHelper;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.network.entity.EmptyEntity;
import com.yylending.las.Global;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
import rx.Observable;
import rx.Subscriber;

/**
 * 需要加密的页面的p需要继承此presenter
 */
public abstract class RSAEncodePresenter<M extends Model, V extends IView> extends Presenter<M, V> {
	private static final String TAG = RSAEncodePresenter.class.getSimpleName();
	public final static int METHOD_RSA = -2;

	@Override
	public void execute(final Object params, final int functionalCode, final boolean autoTips, final Object extraParam, final String requestPage) {
		if (!TextUtils.isEmpty(Global.KEY_RSA)) {
			RSAEncodePresenter.super.execute(getRSAParams(params, functionalCode), functionalCode, autoTips, extraParam, requestPage);
		} else {
			mModel.execute(getRSAObservable(), new Subscriber() {
				@Override
				public void onStart() {
					RSAEncodePresenter.super.onStart(false);
				}

				@Override
				public void onCompleted() {
					RSAEncodePresenter.super.onCompleted(false);
					mModel.completed(METHOD_RSA);
				}

				@Override
				public void onError(Throwable e) {
					RSAEncodePresenter.this.onError(e, false, functionalCode);
					mModel.completed(METHOD_RSA);
				}

				@Override
				public void onNext(Object o) {
					//加密
					RSAResult rsaResult = (RSAResult) o;
					if (BaseResultEntity.isResponseSuccess(rsaResult) && null != rsaResult.getData() && !TextUtils.isEmpty(rsaResult.getData().key)) {
						Global.KEY_RSA = rsaResult.getData().key;
						RSAEncodePresenter.super.execute(getRSAParams(params, functionalCode), functionalCode, autoTips, extraParam, requestPage);
					} else {
						mBaseView.onFunctionError(new Exception(rsaResult.getRetMsg()), true, functionalCode);
					}
				}
			}, METHOD_RSA, null, null);
		}
	}

	public Observable getRSAObservable() {
		Service service = (Service) NetworkHelper.createService(Service.class);
		String token = Global.LOGIN_TOKEN;
		return service.getRsa(token, new EmptyEntity());
	}

	private interface Service {
		@POST("server/security/getRSAKey")
		Observable<RSAResult> getRsa(@Header("token") String token, @Body EmptyEntity rsa);
	}

	static class RSAResult extends BaseResultEntity<RsaBean> {
	}

	static class RsaBean {
		public String key;
	}

	/**
	 * 子类实现，对参数进行加密
	 */
	public abstract Object getRSAParams(Object params, int functionalCode);
}